package com.itheima.reggie.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl implements OrdersSerice {
    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    UserService userService;
    @Autowired
    AddressBookService addressBookService;
    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Override
    @Transactional
    public void submit(Orders orders) {
        //查询当前用户的购物车数据

        List<ShoppingCart> shoppingCarts = shoppingCartService.selectListById(orders.getUserId());

        //查询用户数据
        User user = userService.getById(orders.getUserId());

        //查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);


        long orderId = IdWorker.getId();//订单号

        AtomicInteger amount = new AtomicInteger(0);

        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());


        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表插入数据，一条数据
        ordersMapper.insert(orders);

        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetails);

        //清空购物车数据
        shoppingCartService.cleanAllCart(orders.getUserId());
    }

    @Override
    public Page pageOrder(Long userId, int page, int pageSize) {
        //分页条件构造器
        Page pageInfo = new Page(page, pageSize);
        //查询条件构造器
        QueryWrapper queryWrapper = new QueryWrapper<>();
        //细节查询条件构造器
        QueryWrapper<OrderDetail> queryWrapperDe = new QueryWrapper<>();

        //根据userId查询应有的订单
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("order_time");
        List<Orders> orders1 = ordersMapper.selectPage(pageInfo, queryWrapper).getRecords();

        List<OrderDto> orderDtos = orders1.stream().map((item) -> {
            OrderDto orderDto = new OrderDto();
            orderDto.setId(item.getId());
            orderDto.setUserId(item.getUserId());
            orderDto.setOrderTime(item.getOrderTime());
            orderDto.setStatus(item.getStatus());
            queryWrapperDe.eq("order_id", item.getId());
            List<OrderDetail> orderDetails1 = orderDetailMapper.selectList(queryWrapperDe);
            orderDto.setOrderDetails(orderDetails1);
            queryWrapperDe.clear();
            orderDto.setAmount(item.getAmount());
            orderDto.setSumNum(orderDetails1.size() + 1);
            return orderDto;
        }).collect(Collectors.toList());
        Page<OrderDto> ordersPage = new Page<>();
        ordersPage.setRecords(orderDtos);
        return ordersPage;
    }

    @Override
    public Page pageAllOrder(int page, int pageSize, Integer number, LocalDateTime beginTime, LocalDateTime endTime){
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        QueryWrapper<OrderDetail> queryWrapperDe = new QueryWrapper<>();
        if (number != null) {
            queryWrapper.like("number", number);
        }
        if (beginTime != null && endTime != null) {
            queryWrapper.gt("order_time",beginTime).lt("order_time",endTime);
        }
        List<Orders> orders = ordersMapper.selectPage(pageInfo, queryWrapper).getRecords();
        List<OrderExtend> orderExtends = orders.stream().map((item) -> {
            OrderExtend orderExtend = new OrderExtend();
            BeanUtils.copyProperties(item,orderExtend);
            queryWrapperDe.eq("order_id", item.getId());
            List<OrderDetail> orderDetails1 = orderDetailMapper.selectList(queryWrapperDe);
            orderExtend.setOrderDetails(orderDetails1);
            queryWrapperDe.clear();
            orderExtend.setSumNum(orderDetails1.size() + 1);
            return orderExtend;
        }).collect(Collectors.toList());
        Page<OrderExtend> ordersPage = new Page<>();
        ordersPage.setRecords(orderExtends);
        return ordersPage;
    }

    @Override
    public void updateStatusById(Long id, Long status) {
        Orders orders = ordersMapper.selectById(id);
        orders.setStatus(Math.toIntExact(status));
        ordersMapper.updateById(orders);
    }
}
